#!/bin/sh

cleanup () {
  unset -f chpwd nvm_cd_root_chpwd cd
  unset chpwd_functions NVM_CD_FLAGS CDPATH
}
die () { echo "$@" ; cleanup ; exit 1; }

: nvm.sh
\. ../../../nvm.sh

# `--bogus` makes `cd` fail in every shell if nvm_cd_root ever passed it through
NVM_CD_FLAGS='--bogus'
export NVM_CD_FLAGS
unset CDPATH

# zsh runs these on every directory change unless `cd -q` is used
chpwd () { echo 'chpwd hook ran'; }
nvm_cd_root_chpwd () { echo 'chpwd_functions hook ran'; }
if [ -n "${ZSH_VERSION-}" ]; then
  eval 'chpwd_functions=(nvm_cd_root_chpwd)'
fi

# a user-defined `cd` function must not be called
cd () { echo 'user-defined cd function was called'; return 1; }

START_DIR="$(pwd)"
[ "_${START_DIR}" != '_/' ] || die 'test must not start in /'

OUTPUT="$(nvm_cd_root 2>&1 && pwd)"
[ "_${OUTPUT}" = '_/' ] || die "nvm_cd_root output and resulting directory: got >${OUTPUT}<, expected >/<"

OUTPUT="$(nvm_cd_root 2>&1)"
EXIT_CODE=$?
[ "_${EXIT_CODE}" = '_0' ] || die "nvm_cd_root: got exit code >${EXIT_CODE}<, expected >0<"
[ "_${OUTPUT}" = '_' ] || die "nvm_cd_root: got output >${OUTPUT}<, expected nothing"

nvm_cd_root > /dev/null 2>&1 || die 'nvm_cd_root failed when called directly'
[ "_$(pwd)" = '_/' ] || die "nvm_cd_root did not change the caller's directory: got >$(pwd)<, expected >/<"
[ "_${PWD}" = '_/' ] || die "nvm_cd_root did not update PWD: got >${PWD}<, expected >/<"
nvm_cd "${START_DIR}" > /dev/null 2>&1 || die "could not return to >${START_DIR}<"

# arguments passed to nvm_cd, and its exit status propagating
OUTPUT="$(
  nvm_cd () { echo "args: $*"; return 3; }
  nvm_cd_root
  echo "status: $?"
)"
if [ -n "${ZSH_VERSION-}" ]; then
  EXPECTED="args: -q /
status: 3"
else
  EXPECTED="args: /
status: 3"
fi
[ "_${OUTPUT}" = "_${EXPECTED}" ] || die "nvm_cd_root with a mocked nvm_cd: got >${OUTPUT}<, expected >${EXPECTED}<"

cleanup
